package com.example.demo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.myclover.db.bean.Person;
import com.myclover.db.bean.States;
import com.myclover.db.service.DBService;

public class Demo extends Activity
{
	private DBService dbService;
	private AlertDialog.Builder dialog;
	private AlertDialog.Builder show;

	private EditText et_id;
	private EditText et_name1;
	private EditText et_name2;
	private EditText et_cell;
	private EditText et_home;
	private EditText et_email;
	private EditText et_regdate;
	private EditText et_memo;
	private RadioButton male;
	private RadioButton female;
	private Button btnDatePicker;
	private EditText et_addr1;
	private EditText et_addr2;
	private EditText et_city;
	private EditText et_zip;
	private EditText et_search;
	private TextView tv_page;
	private TextView tv_pagecount;

	// about state button
	private Button btn_state;
	private Button btn_states_dialog_ok, btn_states_dialog_cancel,
			btn_states_dialog_search;
	private ListView lv_states_dialog_list;
	private List<States> listStates;
	private StateAdapter stateAdapter;
	private EditText et_states_dialog_search;
	private ArrayList<HashMap<String, Object>> listitemstate;
	private Dialog stateDialog;
	// ---end---

	private Button btn_add;
	private Button btn_delete;
	private Button btn_save;
	private Button btn_undo;
	private Button btn_exit;
	private Button btn_search;
	private Button btn_export;

	private ImageButton btn_back;
	private ImageButton btn_next;

	private ListView lv_listitem;
	private List<Person> listItem;
	private ArrayAdapter<String> lv_adapter;
	private ArrayList<HashMap<String, Object>> listitem;

	private Spinner sp_condition;
	private List<String> sp_list;
	private ArrayAdapter<String> sp_adapter;

	private ArrayAdapter<String> ss_adapter;

	private ListAdapter listAdapter;
	private Calendar cal = Calendar.getInstance();
	private static boolean isAdd = true;

	private int PageCountSize = 0;
	private int page = 1;
	private static final int PageSize = 50;

	private String conStr;
	private String etStr;
	
	private String m;
	private int n;
	private int temp;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		dbService = new DBService(Demo.this);
		initViewInfo();
		initSearchConditionInfo();
		// initStateInfo();
		initFields();
		enableFields(false);
		btnStatus("init");
		display();
	}
	
	public void display()
	{
		bindingDataByPage(0, PageSize);
		getCountSize();
		setPage();
	}

	public void initViewInfo()
	{
		lv_listitem = (ListView) findViewById(R.id.lv_listitem);

		tv_pagecount = (TextView) findViewById(R.id.tv_pagecount);
		tv_page = (TextView) findViewById(R.id.tv_page);
		et_id = (EditText) findViewById(R.id.et_id);
		et_name1 = (EditText) findViewById(R.id.et_name1);
		et_name2 = (EditText) findViewById(R.id.et_name2);
		et_cell = (EditText) findViewById(R.id.et_cell);
		et_home = (EditText) findViewById(R.id.et_home);
		et_email = (EditText) findViewById(R.id.et_email);
		et_regdate = (EditText) findViewById(R.id.et_regdate);
		et_memo = (EditText) findViewById(R.id.et_memo);
		


		male = (RadioButton) findViewById(R.id.male);
		female = (RadioButton) findViewById(R.id.female);
		btnDatePicker = (Button) findViewById(R.id.btnDatePicker);
		et_addr1 = (EditText) findViewById(R.id.et_addr1);
		et_addr2 = (EditText) findViewById(R.id.et_addr2);
		et_city = (EditText) findViewById(R.id.et_city);
		et_zip = (EditText) findViewById(R.id.et_zip);
		et_search = (EditText) findViewById(R.id.et_search);

		// --about state button
		btn_state = (Button) findViewById(R.id.btn_state);
		btn_state.setOnClickListener(listener);

		// ---end---

		btn_add = (Button) findViewById(R.id.btn_add);
		btn_delete = (Button) findViewById(R.id.btn_delete);
		btn_save = (Button) findViewById(R.id.btn_save);
		btn_undo = (Button) findViewById(R.id.btn_undo);
		btn_exit = (Button) findViewById(R.id.btn_exit);
		btn_search = (Button) findViewById(R.id.btn_search);
		btn_export = (Button) findViewById(R.id.btn_export);

		btn_back = (ImageButton) findViewById(R.id.btn_back);
		btn_next = (ImageButton) findViewById(R.id.btn_next);

		btn_add.setOnClickListener(listener);
		btn_delete.setOnClickListener(listener);
		btn_save.setOnClickListener(listener);
		btn_undo.setOnClickListener(listener);
		btn_exit.setOnClickListener(listener);
		btn_search.setOnClickListener(listener);
		btn_export.setOnClickListener(listener);
		btn_back.setOnClickListener(listener);
		btn_next.setOnClickListener(listener);

		btnDatePicker.setOnClickListener(btnListener);

		sp_condition = (Spinner) findViewById(R.id.sp_condition);

		male.setOnCheckedChangeListener(radioListener);
		female.setOnCheckedChangeListener(radioListener);
		male.setChecked(true);
	}
	
	private TextWatcher watcher = new TextWatcher()
	{
		
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after)
		{
			//btnStatus("UpdateFields");
			System.out.println("beforeTextChanged-----watcher"+ "    "+s.length());
			
		}
		public void onTextChanged(CharSequence s, int start, int before, int count)
		{
			System.out.println("onTextChanged-----watcher"+ "    "+s.length());
			
			//et_id.addTextChangedListener(watcherId);
		}
		public void afterTextChanged(Editable s)
		{
			System.out.println("afterTextChanged-----watcher");
		}
	};
	private TextWatcher watcherId = new TextWatcher()
	{
		
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after)
		{
			m = et_id.getText().toString();
			System.out.println("beforeTextChanged-----watcherId");
		}
		public void onTextChanged(CharSequence s, int start, int before, int count)
		{
			//System.out.println(et_id.getText().toString());
			n = Integer.parseInt(et_id.getText().toString());
			temp = n;
			n++;
			System.out.println("onTextChanged-----watcherId");
		}
		public void afterTextChanged(Editable s)
		{
			System.out.println("afterTextChanged-----watcherId");
		}
	};
	
	private View.OnClickListener btnListener = new View.OnClickListener()
	{
		public void onClick(View v)
		{
			if (isAdd)
			{
				new DatePickerDialog(Demo.this, datelistener, cal
						.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal
						.get(Calendar.DAY_OF_MONTH)).show();
				System.out.println(cal.get(Calendar.YEAR)+"   "+cal.get(Calendar.MONTH) + "    "+cal
						.get(Calendar.DAY_OF_MONTH));
			}
			else 
			{
				String date = btnDatePicker.getText().toString().trim();
				if (!"".equals(date))
				{
					String[] arr = date.split("-");
					new DatePickerDialog(Demo.this, datelistener, Integer.valueOf(arr[2]) ,Integer.valueOf(arr[0])-1 ,Integer.valueOf(arr[1])).show();
				}
				else 
				{
					new DatePickerDialog(Demo.this, datelistener, cal
							.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal
							.get(Calendar.DAY_OF_MONTH)).show();
				}
			}
		}
	};

	private DatePickerDialog.OnDateSetListener datelistener = new DatePickerDialog.OnDateSetListener()
	{
		public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3)
		{
			cal.set(Calendar.YEAR, arg1);
			cal.set(Calendar.MONTH, arg2);
			cal.set(Calendar.DAY_OF_MONTH, arg3);
			updateDate();
		}
	};

	private void updateDate()
	{
		SimpleDateFormat df = new SimpleDateFormat("MM-dd-yyyy");
		btnDatePicker.setText(df.format(cal.getTime()));
	}

	public void getCountSize()
	{
		long ItemCount = dbService.getTotalCounts();
		long page = ItemCount % PageSize;
		if (page == 0)
			PageCountSize = (int) (ItemCount / PageSize);
		else
			PageCountSize = (int) ((ItemCount / PageSize) + 1);
		if (PageCountSize == 0)
			PageCountSize = 1;
		tv_pagecount.setText("/" + PageCountSize);
	}
	
	public void getCountSizeById(Integer id)
	{
		long ItemCount = dbService.getTotalCountsById(id);
		long page = ItemCount % PageSize;
		if (page == 0)
			PageCountSize = (int) (ItemCount / PageSize);
		else
			PageCountSize = (int) ((ItemCount / PageSize) + 1);
		if (PageCountSize == 0)
			PageCountSize = 1;
		tv_pagecount.setText("/" + PageCountSize);
	}
	
	public void getCountSizeByName1(String name)
	{
		long ItemCount = dbService.getTotalCountsByName1(name);
		long page = ItemCount % PageSize;
		if (page == 0)
			PageCountSize = (int) (ItemCount / PageSize);
		else
			PageCountSize = (int) ((ItemCount / PageSize) + 1);
		if (PageCountSize == 0)
			PageCountSize = 1;
		tv_pagecount.setText("/" + PageCountSize);
	}
	
	public void getCountSizeByName2(String name)
	{
		long ItemCount = dbService.getTotalCountsByName2(name);
		long page = ItemCount % PageSize;
		if (page == 0)
			PageCountSize = (int) (ItemCount / PageSize);
		else
			PageCountSize = (int) ((ItemCount / PageSize) + 1);
		tv_pagecount.setText("/" + PageCountSize);
	}

	public void setPage()
	{
		String pageStr = (String) tv_page.getText();
		if (pageStr.trim().equals("") || pageStr == null)
			pageStr = "1";

		page = Integer.valueOf(pageStr);
		if (PageCountSize > page)
		{
			btn_next.setVisibility(View.VISIBLE);
		} else
		{
			btn_next.setVisibility(View.INVISIBLE);
		}

		if (PageCountSize > 1 && page > 1)
		{
			btn_back.setVisibility(View.VISIBLE);
		} else
		{
			btn_back.setVisibility(View.INVISIBLE);
		}
	}

	private void initFields()
	{
		et_id.setText(null);
		et_name1.setText(null);
		et_name2.setText(null);
		et_cell.setText(null);
		et_home.setText(null);
		et_email.setText(null);
		et_regdate.setText(null);
		et_memo.setText(null);
		btnDatePicker.setText("Pick Date");
		et_addr1.setText(null);
		et_addr2.setText(null);
		et_city.setText(null);
		et_zip.setText(null);
		et_search.setText(null);
	}

	private void enableFields(boolean b)
	{
		et_id.setEnabled(false);
		et_regdate.setEnabled(false);
		et_name1.setEnabled(b);
		et_name2.setEnabled(b);
		btnDatePicker.setEnabled(b);
		et_cell.setEnabled(b);
		et_home.setEnabled(b);
		et_email.setEnabled(b);
		et_addr1.setEnabled(b);
		et_addr2.setEnabled(b);
		et_city.setEnabled(b);
		
		btn_state.setEnabled(b);
		et_zip.setEnabled(b);
		et_memo.setEnabled(b);

	}

	private void btnStatus(String optr)
	{
		if (optr.equals("init"))
		{
			btn_delete.setEnabled(false);
			btn_save.setEnabled(false);
			btn_undo.setEnabled(false);
			btn_add.setEnabled(true);
			btn_search.setEnabled(true);
		}
		if (optr.equals("Add"))
		{
			btn_delete.setEnabled(false);
			btn_save.setEnabled(true);
			btn_undo.setEnabled(true);
			btn_add.setEnabled(true);
		}
		if (optr.equals("Update"))
		{
			btn_delete.setEnabled(true);
			btn_save.setEnabled(true);
			btn_undo.setEnabled(true);
			btn_add.setEnabled(false);
			
		}
		if (optr.equals("Undo"))
		{
			btn_delete.setEnabled(false);
			btn_save.setEnabled(false);
			btn_undo.setEnabled(false);
			btn_add.setEnabled(true);
		}
		if (optr.equals("UpdateFields"))
		{
			btn_undo.setEnabled(true);
			btn_add.setEnabled(false);
			btn_delete.setEnabled(false);
			btn_save.setEnabled(true);
			btn_exit.setEnabled(true);
		}
	}

	public boolean validate(String str)
	{
		RegexUtil regexUtil = new RegexUtil();
		return regexUtil.isEmail(str);
	}

	public void initSearchConditionInfo()
	{
		SpinnerUtil spinnerUtil = new SpinnerUtil();
		ArrayList<String> sp_list = spinnerUtil.getSp_list();
		sp_adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, sp_list);
		sp_adapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		sp_condition.setAdapter(sp_adapter);

	}

	

	public OnItemClickListener onItemClickListener = new OnItemClickListener()
	{
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id)
		{
			switch (parent.getId())
			{
			case R.id.lv_listitem:
				listAdapter.ScrollToRow(position);
				Integer Id = (Integer) listitem.get(position).get("Id");
				//et_id.addTextChangedListener(watcher);
				//et_name1.addTextChangedListener(watcher);
				//
				update(Id);
				break;
			}
		}
	};
	


	private OnClickListener listener = new View.OnClickListener()
	{
		public void onClick(View v)
		{
			switch (v.getId())
			{
			case R.id.btn_add:
				isAdd = true;
				initFields();
				enableFields(true);
				et_name1.findFocus();
				btnStatus("Add");
				break;

			case R.id.btn_delete:
				delete("Delete", "Do You Want To Delete?");
				break;

			case R.id.btn_save:
				String emailStr = et_email.getText().toString().trim();
				if (!"".equals(emailStr))
				{
					if (validate(emailStr))
					{
						save("Save", "Do You Want To Save?");
					} else
					{
						Toast("Invalid Email Format!");
						return;
					}
				} else
				{
					save("Save", "Do You Want To Save?");
				}
				break;
			case R.id.btn_undo:
				initFields();
				btnStatus("Undo");
				enableFields(false);
				break;

			case R.id.btn_exit:
				onDestroy();
				exitApp();
				break;
			case R.id.btn_state:
				StateDialogWindow();
				break;
			case R.id.btn_export:
				if ("exportDB".equals(et_search.getText().toString().trim()))
					exportDB();
				if ("restoreDB".equals(et_search.getText().toString().trim()))
					restoreDB();
				
				expCSV("Export CSV File","Customer Data will Export to /mnt/sdcard/MoleQ ");
						
				break;

			case R.id.btn_search:
				conStr = sp_condition.getSelectedItem().toString();
				etStr = et_search.getText().toString().trim();
				// btnStatus("Search");
				tv_page.setText("1");
				if ("All".equals(conStr))
				{
					et_search.setText(null);
					bindingDataByPage(0, PageSize);
					getCountSize();
				}
				if ("Customer Id".equals(conStr))
				{
					RegexUtil regexUtil = new RegexUtil();
					Integer id = null;
					if(regexUtil.isNumber(etStr))
					{
						id = new Integer(Integer.parseInt(etStr));
					}	
					else 
					{
						Toast("Invalid Customer Id!");
						return;
					}
					bindingDataById(id);
					getCountSizeById(id);
				}
				if ("First Name".equals(conStr))
				{
					bindingDataByName1(etStr, 0, PageSize);
					getCountSizeByName1(etStr);
				}
				if ("Last Name".equals(conStr))
				{
					bindingDataByName2(etStr, 0, PageSize);
					getCountSizeByName2(etStr);
				}
				setPage();
				break;

			case R.id.btn_back:
				conStr = sp_condition.getSelectedItem().toString();
				etStr = et_search.getText().toString().trim();
				page = Integer.valueOf(tv_page.getText().toString().trim());
				tv_page.setText(String.valueOf(page - 1));
				if ("All".equals(conStr))
					bindingDataByPage((page - 2) * PageSize, PageSize);
				if ("First Name".equals(conStr))
					bindingDataByName1(etStr, (page - 2) * PageSize, PageSize);
				if ("Last Name".equals(conStr))
					bindingDataByName2(etStr, (page - 2) * PageSize, PageSize);
				setPage();
				break;
			case R.id.btn_next:
				conStr = sp_condition.getSelectedItem().toString();
				etStr = et_search.getText().toString().trim();
				page = Integer.valueOf(tv_page.getText().toString().trim());
				tv_page.setText(String.valueOf(page + 1));
				if ("All".equals(conStr))
					bindingDataByPage(page * PageSize, PageSize);
				if ("First Name".equals(conStr))
					bindingDataByName1(etStr, page * PageSize, PageSize);
				if ("Last Name".equals(conStr))
					bindingDataByName2(etStr, page * PageSize, PageSize);
				setPage();
				break;
			}
		}
	};

	public void StateDialogWindow()
	{
		bindStateData();
		if (stateDialog == null)
		{
			stateDialog = new Dialog(this, R.style.Transparent_dialog);
			stateDialog.setContentView(R.layout.dialog_perview_states);
		}
		lv_states_dialog_list = (ListView) stateDialog
				.findViewById(R.id.lv_states_dialog_list);
		btn_states_dialog_ok = (Button) stateDialog
				.findViewById(R.id.btn_states_dialog_ok);
		btn_states_dialog_cancel = (Button) stateDialog
				.findViewById(R.id.btn_states_dialog_cancel);
		btn_states_dialog_search = (Button) stateDialog
				.findViewById(R.id.btn_states_dialog_search);
		et_states_dialog_search = (EditText) stateDialog
				.findViewById(R.id.et_states_dialog_search);

		btn_states_dialog_ok.setOnClickListener(OnClickDialogWindowListener);
		btn_states_dialog_cancel.setOnClickListener(OnClickDialogWindowListener);
		btn_states_dialog_search.setOnClickListener(OnClickDialogWindowListener);
		lv_states_dialog_list.setOnItemClickListener(onItemClickDialogWindowListener);
				
		int size = listStates.size();
		if (stateAdapter == null) {
			stateAdapter = new StateAdapter(this, listStates);
			lv_states_dialog_list.setAdapter(stateAdapter);
		} else {
			stateAdapter.setSource(listStates);
			stateAdapter.notifyDataSetChanged();
		}
		
		String stateString = btn_state.getText().toString().trim();
		if (stateString.equals(""))
		{
			stateAdapter.ScrollToRow(0);
			lv_states_dialog_list.setSelection(0);
		} else
		{
			for (int i = 0; i < listStates.size(); i++)
			{
				if (stateString.equals(listStates.get(i).getState_id()))
				{
					stateAdapter.ScrollToRow(i);
					lv_states_dialog_list.setSelection(i);
				}
			}
		}
		stateDialog.show();
	}

	public OnClickListener OnClickDialogWindowListener = new OnClickListener()
	{
		public void onClick(View v)
		{
			switch (v.getId())
			{
			case R.id.btn_states_dialog_ok:
				if (listStates.size() > 0)
				{
					btn_state.setText(listStates.get(
							stateAdapter.GetSelectedIndex()).getState_id());
				}
				stateDialog.dismiss();
				break;
			case R.id.btn_states_dialog_cancel:
				stateDialog.dismiss();
				break;
			case R.id.btn_states_dialog_search:
				String searchStates = et_states_dialog_search.getText().toString();
				listStates = dbService.getStatesById(searchStates);
				stateAdapter.setSource(listStates);
				stateAdapter.notifyDataSetChanged();
				stateAdapter.ScrollToRow(0);
				et_states_dialog_search.setText("");
				break;
			}
		}
	};

	public OnItemClickListener onItemClickDialogWindowListener = new OnItemClickListener()
	{
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id)
		{
			switch (parent.getId())
			{
			case R.id.lv_states_dialog_list:
				stateAdapter.ScrollToRow(position);
				break;
			default:
				break;
			}

		}
	};

	public void bindStateData()
	{
		listStates = dbService.getStates();
	}

	public void expCSV(String title, String message)
	{
		dialog = new AlertDialog.Builder(Demo.this);
		dialog.setTitle(title).setIcon(android.R.drawable.ic_dialog_info)
				.setMessage(message)
				.setPositiveButton("Yes", new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface dialog, int which)
					{
						dbService.exportCSV();
					}
				})
				.setNegativeButton("No", new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface dialog, int which)
					{
						dialog.cancel();
					}
				}).create().show();
	}

	
	public void delete(String title, String message)
	{
		dialog = new AlertDialog.Builder(Demo.this);
		dialog.setTitle(title).setIcon(android.R.drawable.ic_dialog_info)
				.setMessage(message)
				.setPositiveButton("Yes", new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface dialog, int which)
					{
						if (listAdapter.GetSelectedIndex() < 0)
							return;
						Integer Id = (Integer) listitem.get(
								listAdapter.GetSelectedIndex()).get("Id");
						dbService.delete(Id);
						if (listitem != null && listitem.size() > 0)
							display();
						initFields();
					}
				})
				.setNegativeButton("No", new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface dialog, int which)
					{
						dialog.cancel();
					}
				}).create().show();
	}
	
	public void save(String title, String message)
	{
		dialog = new AlertDialog.Builder(Demo.this);
		dialog.setTitle(title).setIcon(android.R.drawable.ic_dialog_info)
				.setMessage(message)
				.setPositiveButton("Yes", new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface dialog, int which)
					{
						Person p = getPerson();
						if (isAdd)
						{
							dbService.save(p);
						}
						else
						{
							if (p.getId()==0)
							{
								Toast("No Record is Updated! Please Choose a Valid Record!");
								return;
							}else 
							{
								dbService.update(p);
							}
						}
						if (listitem != null && listitem.size() > 0)
							display();
						initFields();
					}
				})
				.setNegativeButton("No", new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface dialog, int which)
					{
						dialog.cancel();
					}
				}).create().show();
	}

	public Person getPerson()
	{
		Person p = new Person();
		if (!isAdd)
		{
			if ("".equals(et_id.getText().toString().trim()))
				p.setId(0);
			else
				p.setId(Integer.parseInt(et_id.getText().toString().trim()));
		}
		p.setRegdate(et_regdate.getText().toString().trim());
		p.setFirstname(et_name1.getText().toString().trim());
		p.setLastname(et_name2.getText().toString().trim());
		if (male.isChecked())
			p.setSex("M");
		else
			p.setSex("F");

		if (btnDatePicker.getText().toString().trim() == "Pick Date")
			p.setDob("");
		else 
			p.setDob(btnDatePicker.getText().toString().trim());
		p.setCellphone(et_cell.getText().toString().trim());
		p.setHomephone(et_home.getText().toString().trim());
		p.setEmail(et_email.getText().toString().trim());
		p.setAddr1(et_addr1.getText().toString().trim());
		p.setAddr2(et_addr2.getText().toString().trim());
		p.setCity(et_city.getText().toString().trim());
		if ("State".equals(btn_state.getText().toString().trim()))
			p.setState("");
		else 
			p.setState(btn_state.getText().toString().trim());
		p.setZip(et_zip.getText().toString().trim());
		p.setMemo(et_memo.getText().toString().trim());
		p.setF01("");
		p.setF02("");

		return p;
	}

	public void update(Integer Id)
	{
		isAdd = false;
		enableFields(true);
		btnStatus("Update");
		Person person = dbService.findById(Id);
		if (person != null)
		{
			et_id.setText(String.valueOf(person.getId()));
			et_regdate.setText(person.getRegdate());
			et_name1.setText(person.getFirstname());
			et_name2.setText(person.getLastname());
			if ("M".equals(person.getSex()))
			{
				male.setChecked(true);
				female.setChecked(false);
			}
			else 
			{
				female.setChecked(true);
				male.setChecked(false);
			}
			btnDatePicker.setText(person.getDob());
			et_cell.setText(person.getCellphone());
			et_home.setText(person.getHomephone());
			et_email.setText(person.getEmail());
			et_addr1.setText(person.getAddr1());
			et_addr2.setText(person.getAddr2());
			et_city.setText(person.getCity());
			btn_state.setText(person.getState());
			et_zip.setText(person.getZip());
			et_memo.setText(person.getMemo());
			btnDatePicker.setOnClickListener(btnListener);
		}
	}

	// --begin-----binding data------
	public void bindingDataAll()
	{

		if (listitem == null)
		{
			listitem = new ArrayList<HashMap<String, Object>>();
			HashMap<String, Object> map = null;
			List<Person> lp = dbService.findAll();
			for (Person person : lp)
			{
				map = new HashMap<String, Object>();
				map.put("Id", person.getId());
				map.put("firstname", person.getFirstname());
				map.put("lastname", person.getLastname());
				map.put("email", person.getEmail());
				listitem.add(map);
			}
			listAdapter = new ListAdapter(this, listitem);
			lv_listitem.setAdapter(listAdapter);
			lv_listitem.setOnItemClickListener(onItemClickListener);
		} else
		{
			listitem.clear();
			HashMap<String, Object> map = null;
			List<Person> lp = dbService.findAll();
			for (Person person : lp)
			{
				map = new HashMap<String, Object>();
				map.put("Id", person.getId());
				map.put("firstname", person.getFirstname());
				map.put("lastname", person.getLastname());
				map.put("email", person.getEmail());
				listitem.add(map);
			}
			listAdapter.setSource(listitem);
			listAdapter.notifyDataSetChanged();
		}
	}

	public void bindingDataByPage(int startNum, int perNum)
	{
		if (listitem == null)
		{
			listitem = new ArrayList<HashMap<String, Object>>();
			HashMap<String, Object> map = null;
			List<Person> lp = dbService.getPerosns(startNum, perNum);
			for (Person person : lp)
			{
				map = new HashMap<String, Object>();
				map.put("Id", person.getId());
				map.put("firstname", person.getFirstname());
				map.put("lastname", person.getLastname());
				map.put("email", person.getEmail());
				listitem.add(map);
			}
			listAdapter = new ListAdapter(this, listitem);
			lv_listitem.setAdapter(listAdapter);
			lv_listitem.setOnItemClickListener(onItemClickListener);
		} else
		{
			listitem.clear();
			HashMap<String, Object> map = null;
			List<Person> lp = dbService.getPerosns(startNum, perNum);
			for (Person person : lp)
			{
				map = new HashMap<String, Object>();
				map.put("Id", person.getId());
				map.put("firstname", person.getFirstname());
				map.put("lastname", person.getLastname());
				map.put("email", person.getEmail());
				listitem.add(map);
			}
			listAdapter.setSource(listitem);
			listAdapter.notifyDataSetChanged();
		}
	}

	public void bindingDataById(Integer Id)
	{
		if (listitem == null)
		{
			listitem = new ArrayList<HashMap<String, Object>>();
			HashMap<String, Object> map = null;
			Person person = dbService.findById(Id);
			map = new HashMap<String, Object>();
			map.put("Id", person.getId());
			map.put("firstname", person.getFirstname());
			map.put("lastname", person.getLastname());
			map.put("email", person.getEmail());
			listitem.add(map);

			listAdapter = new ListAdapter(this, listitem);
			lv_listitem.setAdapter(listAdapter);
			lv_listitem.setOnItemClickListener(onItemClickListener);
		} else
		{
			listitem.clear();
			HashMap<String, Object> map = null;
			Person person = dbService.findById(Id);
			map = new HashMap<String, Object>();
			map.put("Id", person.getId());
			map.put("firstname", person.getFirstname());
			map.put("lastname", person.getLastname());
			map.put("email", person.getEmail());
			listitem.add(map);

			listAdapter.setSource(listitem);
			listAdapter.notifyDataSetChanged();
		}
	}

	public void bindingDataByName1(String name, int startNum, int perNum)
	{
		if (listitem == null)
		{
			listitem = new ArrayList<HashMap<String, Object>>();
			HashMap<String, Object> map = null;
			List<Person> lp = dbService.findByName1(name, startNum, perNum);
			for (Person person : lp)
			{
				map = new HashMap<String, Object>();
				map.put("Id", person.getId());
				map.put("firstname", person.getFirstname());
				map.put("lastname", person.getLastname());
				map.put("email", person.getEmail());
				listitem.add(map);
			}
			listAdapter = new ListAdapter(this, listitem);
			lv_listitem.setAdapter(listAdapter);
			lv_listitem.setOnItemClickListener(onItemClickListener);
		} else
		{
			listitem.clear();
			HashMap<String, Object> map = null;
			List<Person> lp = dbService.findByName1(name, startNum, perNum);
			for (Person person : lp)
			{
				map = new HashMap<String, Object>();
				map.put("Id", person.getId());
				map.put("firstname", person.getFirstname());
				map.put("lastname", person.getLastname());
				map.put("email", person.getEmail());
				listitem.add(map);
			}
			listAdapter.setSource(listitem);
			listAdapter.notifyDataSetChanged();
		}
	}

	public void bindingDataByName2(String name, int startNum, int perNum)
	{
		if (listitem == null)
		{
			listitem = new ArrayList<HashMap<String, Object>>();
			HashMap<String, Object> map = null;
			List<Person> lp = dbService.findByName2(name, startNum, perNum);
			for (Person person : lp)
			{
				map = new HashMap<String, Object>();
				map.put("Id", person.getId());
				map.put("firstname", person.getFirstname());
				map.put("lastname", person.getLastname());
				map.put("email", person.getEmail());
				listitem.add(map);
			}
			listAdapter = new ListAdapter(this, listitem);
			lv_listitem.setAdapter(listAdapter);
			lv_listitem.setOnItemClickListener(onItemClickListener);
		} else
		{
			listitem.clear();
			HashMap<String, Object> map = null;
			List<Person> lp = dbService.findByName2(name, startNum, perNum);
			for (Person person : lp)
			{
				map = new HashMap<String, Object>();
				map.put("Id", person.getId());
				map.put("firstname", person.getFirstname());
				map.put("lastname", person.getLastname());
				map.put("email", person.getEmail());
				listitem.add(map);
			}
			listAdapter.setSource(listitem);
			listAdapter.notifyDataSetChanged();
		}
	}

	// --end-----binding data------
	private void restoreDB()
	{
		System.out.println("begin");
		String databaseFilename = "//data//data//com.example.demo//databases//person.db";
		String DATABASE_NAME = "person.db";
		File dbPath = new File("//data//data//com.example.demo//databases//");
		File dbFile = new File(databaseFilename);
		
		String SDCARD = android.os.Environment.getExternalStorageDirectory()
				.getAbsolutePath();
		File SDCARD_DB_PATH = new File(SDCARD + "/MoleQ/db/");
		File SDCARD_DB_FILENAME = new File(SDCARD_DB_PATH + "/" + DATABASE_NAME);
		
		try
		{
			if(dbFile.exists())
			{
				System.out.println("dbFile.exists()");
				dbFile.delete();
			}
			/*
			System.out.println("restoreDB");
			InputStream is = new FileInputStream(SDCARD_DB_FILENAME);
			FileOutputStream fos = new FileOutputStream(dbFile);
			byte[] buffer = new byte[8192];
			int count = 0;
			while ((count=is.read(buffer))>0)
			{
				fos.write(buffer, 0, count);
			}
			fos.flush();
			fos.close();
			is.close();
			Toast("Restore is Done!");
			*/
			
		} catch (Exception e)
		{
			Toast(e.getMessage());
		}
	}
	
	
	private void exportDB()
	{
		String databaseFilename = "//data//data//com.example.demo//databases//person.db";
		String DATABASE_NAME = "person.db";
		File dbPath = new File("//data//data//com.example.demo//databases//");
		File dbFile = new File(databaseFilename);

		String SDCARD = android.os.Environment.getExternalStorageDirectory()
				.getAbsolutePath();
		File SDCARD_DB_PATH = new File(SDCARD + "/MoleQ/db/");
		File SDCARD_DB_FILENAME = new File(SDCARD_DB_PATH + "/" + DATABASE_NAME);

		if (!SDCARD_DB_PATH.exists())
		{
			SDCARD_DB_PATH.mkdirs();
			Log.i("LogDemo", "sdcard db path mkdir");
		}

		try
		{
			if (SDCARD_DB_FILENAME.exists())
			{
				SDCARD_DB_FILENAME.delete();
			}
			if (!SDCARD_DB_FILENAME.exists())
			{
				InputStream is = new FileInputStream(new File(databaseFilename));
				FileOutputStream fos = new FileOutputStream(SDCARD_DB_FILENAME);

				byte[] buffer = new byte[8192];
				int count = 0;
				while ((count = is.read(buffer)) > 0)
				{
					fos.write(buffer, 0, count);
				}
				fos.close();
				is.close();
				Log.i("LogDemo", "Backup database completed.");
				Toast("Database Path -->" + databaseFilename);
			}
		} catch (Exception e)
		{
			Toast(e.getMessage());
		}
	}

	private OnCheckedChangeListener radioListener = new OnCheckedChangeListener()
	{

		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked)
		{
			RadioButton rbtn = (RadioButton) buttonView;
			switch (rbtn.getId())
			{
			case R.id.male:
				if (isChecked)
				{
					male.setChecked(true);
					female.setChecked(false);
				}
				break;
			case R.id.female:
				if (isChecked)
				{
					male.setChecked(false);
					female.setChecked(true);
				}
				break;
			}

		}
	};

	public void Toast(String str)
	{
		Toast.makeText(Demo.this, str, Toast.LENGTH_LONG).show();
	}

	@Override
	protected void onDestroy()
	{
		if (dbService != null)
		{
			dbService.closeDB();
		}
		super.onDestroy();
	}

	public void Keyboard()
	{
		InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		inputMethodManager.hideSoftInputFromWindow(Demo.this.getCurrentFocus()
				.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
	}

	private void exitApp()
	{
		dialog = new AlertDialog.Builder(Demo.this);
		dialog.setTitle("Close Application")
				.setIcon(android.R.drawable.ic_dialog_info)
				.setMessage("Do you want to close it?")
				.setPositiveButton("Yes", new DialogInterface.OnClickListener()
				{

					public void onClick(DialogInterface dialog, int which)
					{
						finish();
						System.exit(0);
					}
				})
				.setNegativeButton("No", new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface dialog, int which)
					{
						dialog.cancel();
					}
				}).create().show();
	}

}

